<template>
  <div class="my-info">
    <h1 style="font-size: 20px">个人中心</h1>
    <el-form label-width="100px" class="my-info-form" @submit.native.prevent="updateUser">
      <el-form-item label="用户ID:">
        {{ user.id }}
      </el-form-item>
      <el-form-item label="用户名:">
        <el-input v-model="user.username" placeholder="用户名"></el-input>
      </el-form-item>
      <el-form-item label="邮箱:">
        <el-input v-model="user.email" placeholder="邮箱"></el-input>
      </el-form-item>
      <el-form-item label="创建时间:">
        {{ user.createdAt}}
      </el-form-item>
      <el-form-item label="年级:">
        <el-input v-model="user.grade" placeholder="年级"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">保存修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: {
        id: '',
        username: '',
        email: '',
        createdAt: '',
        grade: ''
      }
    };
  },
  created() {
    this.fetchUser();
  },
  methods: {
    fetchUser() {
      const username = localStorage.getItem('username');
      axios.get(`http://localhost:8080/users/findByUsername?username=${username}`)
          .then(response => {
            this.user = response.data;
          })
          .catch(error => {
            console.error('Error fetching user:', error);
            this.$message.error('用户信息加载失败');
          });
    },
    updateUser() {
      axios.put(`http://localhost:8080/users/update/${this.user.id}`, this.user)
          .then(response => {
            this.$message.success('用户信息更新成功');
          })
          .catch(error => {
            console.error('Error updating user:', error);
            this.$message.error('用户信息更新失败');
          });
    }
  },
  filters: {
    formatDate(value) {
      if (!value) return '';
      const date = new Date(value);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    }
  }
};
</script>

<style scoped>
.my-info {
  padding: 20px;
  max-width: 600px; /* 限制最大宽度 */
}

.my-info-form {
  padding-top: 100px; /* 减少顶部内边距 */
}

.my-info-form {
  margin-bottom: 24px; /* 增加表单项之间的间距 */
  line-height: 2; /* 增加行高 */
}

/* 可以为表单项的外框添加边框和圆角，使其更突出 */
.my-info-form .el-form-item {
  border: 1px solid #ffffff; /* 边框颜色 */
  border-radius: 4px; /* 圆角 */
  padding: 12px; /* 内边距 */
  background-color: #ffffff; /* 背景色 */
  font-size: 20px; /* 增加字体大小 */
}
</style>